package com.kof.picviewer;

import javafx.application.Application;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Map;
@SuppressWarnings("restriction")
public class MainApplication extends Application {

    private WebEngine webEngine;
    public static Stage primaryStage;
    private ApplicationContext context;

    @Override
    public void init() {
        // 启动HTTP服务器
        StaticHtmlServer.runHttpServer();
        // 初始化Spring应用上下文
         context = new AnnotationConfigApplicationContext("com.kof.picviewer");
    }

    public void initServices(JSObject window) {
        // 从Spring应用上下文中获取所有@Service注解的Bean
        Map<String, Object> serviceBeans = context.getBeansWithAnnotation(Service.class);

        // 遍历所有@Service注解的Bean
        for (Map.Entry<String, Object> entry : serviceBeans.entrySet()) {
            String beanName = entry.getKey();
            Object beanInstance = entry.getValue();
            window.setMember(beanName, beanInstance);
        }


    }
    @Override
    public void start(Stage primaryStage) throws Exception {
        this.primaryStage = primaryStage;
        primaryStage.getIcons().add(new Image((getClass().getResourceAsStream("/icon/icon.png"))));
        primaryStage.setTitle("图片浏览器");
        WebView webView = new WebView();
        webEngine = webView.getEngine();

        // 设置Java的监听器
        webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
            if (Worker.State.SUCCEEDED == newValue) {
                // 在web引擎页面中设置一个名为“javaConnector”的接口对象
                JSObject window = (JSObject) webEngine.executeScript("window");
                initServices(window);
            }else if (Worker.State.FAILED == newValue) {
                System.out.println("加载失败: " + webEngine.getLocation());
                Throwable exception = webEngine.getLoadWorker().getException();
                if (exception != null) {
                    exception.printStackTrace();
                }
            }
        });

        Scene scene = new Scene(webView, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();

        // 这里加载页面
        webEngine.load(StaticHtmlServer.HTTP_SERVER_URL);
        // 调试启动本地服务
        //webEngine.load("http://localhost:5173");

    }

    public static void main(String[] args) {
        launch(args);
    }

}
